package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.adapters.TenderAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.SkAlertDialog
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/4/25  17:11
 *  @desc 收藏
 */
class CollectionActivity : BaseActiivity() {

    @LCBindView(R.id.ac_comment_recyclerview)
    private lateinit var recyclerView: RecyclerView

    @LCBindView(R.id.ac_swipe_refreshLayout)
    private var pullRefreshLayout: SKPullRefreshLayout? = null

    private lateinit var tenderAdapter: TenderAdapter
    private var list = ArrayList<TenderModel>()
    private var deleteDialog: SkAlertDialog? = null
    private var currentPosition = 0
    private var currentPage = 1
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_list_refresh)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("兴趣收藏")
        initAdapter()
    }


    private fun initAdapter() {
        pullRefreshLayout!!.onStartListener = refreshListener
        pullRefreshLayout!!.onStartListener.onStartRefresh(pullRefreshLayout)
        recyclerView.layoutManager = LinearLayoutManager(mContext)
        tenderAdapter = TenderAdapter(mContext, 1, list, mOnItemClickListener)
        recyclerView.adapter = tenderAdapter
    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val resId = args[0] as Int
            currentPosition = args[1] as Int
            when (resId) {
                R.id.item_root_layout -> {
                    val intent = Intent(mContext, SyDetailActivity::class.java)
                    intent.putExtra("tender_id", list[currentPosition].wasteInformationId)
                    startActivity(intent)
                }

                R.id.item_tender_delete -> {
                    showAlert()
                }
            }
        }
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 删除提醒
     */
    private fun showAlert() {
        if (deleteDialog == null) {
            deleteDialog = SkAlertDialog(mContext)
            deleteDialog!!.setOnclickListener(mDeleteOnclickListener)
        }
        deleteDialog!!.setTitleAndContent("删除提醒", "确实要删除此条收藏吗？")
        deleteDialog!!.showExpend()
    }


    private val mDeleteOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            unCollection(list[currentPosition].id)
        }
    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            requestData()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            currentPage++
            requestData()
        }
    }

    /**
     *  @time 2025/1/22  11:22
     *  @author Im_jingwei
     *  @desc 请求数据
     */
    fun requestData() {
        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_COLLECTION
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", currentPage)
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                freshOrLoadFaild()
                LCBaseUtil.showToast(mContext, "请求云端数据失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    if (currentPage == 1) {
                        list.clear()
                    }
                    if (success) {
                        runOnUiThread {
                            fresOrLoadSuccess(data.length())
                            for (index in 0 until data.length()) {
                                val item = TenderModel().apply { getModelInfo(data.getJSONObject(index)) }
                                list.add(item)
                            }
                            tenderAdapter.notifyDataSetChanged()
                        }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(mContext, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(mContext, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 取消收藏
     *  @param url
     */
    private fun unCollection(favoriteId: String?) {
        if (favoriteId.isNullOrEmpty()) {
            return
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_UNCOLLCTION
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("id", favoriteId)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                showToast("取消失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
//                        requestData()
                        runOnUiThread {
                            list.removeAt(currentPosition)
                            tenderAdapter.notifyDataSetChanged()
                        }
                        showToast("已取消收藏！")
                        LCLogger.d(TAG, "获取成功！,数据：$jsonObject")
                    } else {
                        showToast("取消失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    showToast("取消失败，" + e.message)
                }
            }
        })
    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout!!.refreshSuccess()
            list.clear()
        } else {
            pullRefreshLayout!!.loadmoreSuccess()
        }
        if (rows == AppConfig.PAGE_SIZE) {
            pullRefreshLayout!!.isLoadmoreable = true
        } else {
            pullRefreshLayout!!.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        runOnUiThread {
            if (currentPage == 1) {
                //            pullRefreshLayout.stopRefresh()
                //                pullRefreshLayout.refreshSuccess();
                pullRefreshLayout!!.refreshFailed();
            } else {
                //                pullRefreshLayout.loadmoreSuccess()
                pullRefreshLayout!!.loadmoreFailed()
            }
        }
    }


}